/**
 * 全局 Loading 工具
 * 使用 van-loading 组件封装
 */
import { createApp, h, ref } from 'vue'
import Vant from 'vant'
import GlobalLoading from '@/components/GlobalLoading.vue'

let loadingInstance = null
let loadingApp = null
let container = null

/**
 * 显示全局 loading
 * @param {Object} options 配置选项
 * @param {String} options.message 提示文字
 * @param {String} options.size loading 大小，默认 '24px'
 * @param {String} options.color loading 颜色，默认 '#1989fa'
 */
export const showLoading = (options = {}) => {
  // 如果已经存在实例，先关闭
  if (loadingInstance) {
    hideLoading()
  }

  // 创建容器
  container = document.createElement('div')
  container.id = 'global-loading-container'
  document.body.appendChild(container)

  // 创建响应式数据
  const visible = ref(true)
  const message = ref(options.message || '')
  const size = ref(options.size || '32px')
  const color = ref(options.color || '#7C96A6')

  // 创建新的 Vue 应用实例
  loadingApp = createApp({
    setup() {
      return () => h(GlobalLoading, {
        visible: visible.value,
        message: message.value,
        size: size.value,
        color: color.value
      })
    }
  })
  
  // 注册 Vant 组件
  loadingApp.use(Vant)

  // 挂载组件
  loadingApp.mount(container)
  
  // 保存响应式引用和容器引用
  loadingInstance = {
    visible,
    message,
    size,
    color,
    container,
    app: loadingApp
  }
}

/**
 * 隐藏全局 loading
 */
export const hideLoading = () => {
  if (loadingInstance) {
    // 隐藏 loading
    loadingInstance.visible.value = false

    // 延迟卸载，确保动画完成
    setTimeout(() => {
      if (loadingInstance && loadingInstance.app && loadingInstance.container) {
        loadingInstance.app.unmount()
        if (loadingInstance.container.parentElement) {
          loadingInstance.container.parentElement.removeChild(loadingInstance.container)
        }
        loadingApp = null
        container = null
        loadingInstance = null
      }
    }, 300)
  }
}

export default {
  show: showLoading,
  hide: hideLoading
}

